﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebGrease.Activities;
using  System.Net;
using Kickstarter.Models;

namespace WebTV_Kickstarter
{
    [MetadataType(typeof(Gebruiker_Validator))]
    public partial class Gebruiker
    {
        private static EFDataModelContainer tempContainer = null;

        static public List<Gebruiker> GetAllGebruikers()
        {
            EFDataModelContainer efDataModelContainer = new EFDataModelContainer();
            return efDataModelContainer.GebruikerSet.ToList();
        }

        //Vind gebruiker met ID
        static public Gebruiker FindGebruiker(int? id)
        {
             EFDataModelContainer db = new EFDataModelContainer();
             tempContainer = db;
             return db.GebruikerSet.Find(id);
        }

        public static Gebruiker FindGebruikerWithDbContainer(int id, EFDataModelContainer tempContainer)
        {
            return tempContainer.GebruikerSet.Find(id);
        }

        //Vind gebruiker met Email en Wachtwoord
        public static Gebruiker FindGebruiker(Gebruiker login)
        {
            EFDataModelContainer db = new EFDataModelContainer();
            IQueryable<Gebruiker> gebruikers = db.GebruikerSet;

            Gebruiker[] gebruikersArray =
                (
                    from g in gebruikers
                    where g.Email == login.Email && g.Wachtwoord == login.Wachtwoord
                    select g
                    ).ToArray();

            if (gebruikersArray.Length == 1)
            {
                tempContainer = db;
                return gebruikersArray[0];
            }
            else
            {
                return null;
            }
        }

        static public void AddGebruiker(Gebruiker g)
        {

            g.TotalDonated = 0;
            g.isAdmin = false;

            g.Wachtwoord = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(g.Wachtwoord)));
                EFDataModelContainer db = new EFDataModelContainer();
                db.GebruikerSet.Add(g);

            List<string> errors = new List<string>();
            try
            {
                db.SaveChanges();   
            } catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errors.Add(validationError.PropertyName + " + " + validationError.ErrorMessage);
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
        }

        static public void EditGebruikerForDonation(Gebruiker gebruiker)
        {
            EFDataModelContainer db = null;

            if (tempContainer != null)
            {
                db = tempContainer;
                //db.Entry(gebruiker).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        static public void EditGebruikerForEdit(Gebruiker gebruiker)
        {
            EFDataModelContainer db = new EFDataModelContainer();
            db.Entry(gebruiker).State = EntityState.Modified;
            db.SaveChanges();
        }

        static public void EditGebruiker(Gebruiker gebruiker)
        {
            EFDataModelContainer db = null;

            if (tempContainer != null)
            {
                db = tempContainer;
                db.Entry(gebruiker).State = EntityState.Modified;
                db.SaveChanges();
            }
        }



        static public void Dispose()
        {
            EFDataModelContainer db = new EFDataModelContainer();
            db.Dispose();
        }

        public static void RemoveGebruiker(int id)
        {
            EFDataModelContainer db = null;
            Gebruiker g = FindGebruiker(id);

            if (tempContainer != null)
            {
                db = tempContainer;
                tempContainer = null;
                db.GebruikerSet.Remove(g);
                db.SaveChanges();
            }
        }

        public static void EditDonation(Gebruiker gebruiker)
        {
            EFDataModelContainer db = new EFDataModelContainer();
            //db.Entry(gebruiker).State = EntityState.Modified;
            db.SaveChanges();
        }

        public static Gebruiker FindGebruikerByEmail(string email)
        {
            EFDataModelContainer db = new EFDataModelContainer();
            IQueryable<Gebruiker> gebruikers = db.GebruikerSet;

            Gebruiker[] gebruikersArray =
                (
                    from g in gebruikers
                    where g.Email == email
                    select g
                    ).ToArray();

            if (gebruikersArray.Length == 1)
            {
                tempContainer = db;
                return gebruikersArray[0];
            }
            else
            {
                return null;
            }
        }

        public static void EditGebruikerWachtwoord(string email)
        {
            string newPassword = "";
            Gebruiker gebruiker = FindGebruikerByEmail(email);
            newPassword = GenerateNewPassword();
            gebruiker.Wachtwoord = ConvertPassword(newPassword);
            EditGebruiker(gebruiker);

            SendEmail(gebruiker.Email, newPassword);
        }

        private static string GenerateNewPassword()
        {
            string tempPassword = "";
            string[] characters = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"
                                  ,"g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x"
                                  ,"y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P"
                                  ,"Q","R","S","T","U","V","W","X","Y","Z","@","#","!","-","_","{","}",":"};

            Random number = new Random();
            int getal;

            // Elk random wachtwoord heeft 10 tekens
            for (int i = 0; i <= 9; i++)
            {
                getal = number.Next(0, 70);
                tempPassword = tempPassword + characters[getal];
            }
            return tempPassword;
        }

        private static void SendEmail(string p, string newPassword)
        {
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.To.Add(p);
            message.Subject = "New password";
            message.From = new System.Net.Mail.MailAddress("webtv@josplays.com");
            message.Body = "Your new password is: " + newPassword + "\t\rDo not reply to this email.";
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("mail.josplays.com", 587);
            smtp.Credentials = new System.Net.NetworkCredential("webtv@josplays.com", "JH1O1sZe");
            smtp.Send(message);
        }

        public static string ConvertPassword(string p)
        {
            string encryptedPassword = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(p)));
            return encryptedPassword;
        }

        public static void Login(Gebruiker login)
        {
            login.Wachtwoord = ConvertPassword(login.Wachtwoord);
            Gebruiker g = FindGebruiker(login);
            HttpContext.Current.Session["gebruiker"] = g;
        }

        public static bool IsAdmin()
        {
            Gebruiker g = (Gebruiker)HttpContext.Current.Session["gebruiker"];
            if (g != null)
            {
                return (bool)g.isAdmin;
            }
            else
            {
                return false;
            }
        }
    }
}